package com.fdm.model.DAO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.TreeMap;
import com.fdm.model.accounts._Account;
import com.fdm.model.exceptions.BankManagerException;
import com.fdm.model.exceptions.DAOException;

public class TreeMapDAO implements _AccountDAO
{
	private static Map<Integer,_Account> accounts = new TreeMap<Integer,_Account>();
	
	@Override
	public _Account retrieve(int accountNumber) throws DAOException
	{
		return accounts.get(accountNumber);
	}

	@Override
	public void delete(int accountNumber) throws DAOException
	{
		accounts.remove(accountNumber);
	}

	@Override
	public void create(_Account newAccount) 
	{
		accounts.put(newAccount.getAccountNumber(), newAccount);
	}

	@Override
	public List<_Account> retrieveAll() 
	{
		List<_Account> accountList = new ArrayList<_Account>();
		for(_Account account: accounts.values())
		{
			accountList.add(account);
		}
		return accountList;
	}

	@Override
	public String getStorageType() 
	{
		return "TREEMAP";
	}

	@Override
	public void update(int accountNumber,Double newValue) throws DAOException {
		Map<String,Object> parameters = new TreeMap<String, Object>();
		parameters.put("balance", newValue);
		try {
			this.retrieve(accountNumber).setAttributes(parameters);
		} catch (BankManagerException e) {
			throw new DAOException();
		}		
	}

	@Override
	public int getMaxAccountNumber() throws DAOException {
		try{
			return ((TreeMap<Integer, _Account>) accounts).lastKey();
		}catch (NoSuchElementException e)
		{
			return 10000;
		}
	}
	
}
